package leetcode;

import java.util.*;

/**
 * @author noob
 * @version 1.0
 * @date 2021/3/18 13:15
 * //先统计nuns1中的元素对应的个数  k，count
 */
public class Solution350 {
    public int[] intersect(int[] nums1, int[] nums2) {

        TreeMap<Integer, Integer> map =new TreeMap<>();
        for(int num:nums1){
            if(!map.containsKey(num)){
                map.put(num,1);
            }else{
                map.put(num,map.get(num)+1);
            }
        }



        ArrayList<Integer> list = new ArrayList<>();
        for(int num:nums2){
            if(map.containsKey(num)){
                //添加到list中去，然后把map中的丢掉
                list.add(num);
                map.put(num,map.get(num)-1);
                if(map.get(num) == 0){
                    map.remove(num);
                }
            }
        }

        int[] res = new int[list.size()];
        for (int i = 0; i < list.size(); i++) {
            res[i] = list.get(i);
        }
        return res;


    }


    public static void main(String[] args) {
        int[] nums1 = {1,2,2,1};
        int[] nums2 = {2,2};
        int[] ints = new Solution350().intersect(nums1, nums2);
        for(int n:ints){
            System.out.print(n);
        }
    }
}
